//
//  RegisterViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/17.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "RegisterViewController.h"
#import "UIButton+CountDown.h"
#import "OpenInstallSDK.h"
#import "TTUDIDManager.h"

#import "TT_WebviewController.h"
@interface RegisterViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (weak, nonatomic) IBOutlet UITextField *codeTF;

@property (weak, nonatomic) IBOutlet UITextField *pswTF;
@property (weak, nonatomic) IBOutlet UITextField *checkPswTF;

@property (weak, nonatomic) IBOutlet UIButton *hidePswBtn;
@property (weak, nonatomic) IBOutlet UIButton *hideCheckPswBtn;

//@property (weak, nonatomic) IBOutlet UITextField *recommandTF;

@property (weak, nonatomic) IBOutlet UIButton *countDownBtn;


@property (weak, nonatomic) IBOutlet UILabel *linkText;

@property (nonatomic, assign) BOOL isShowPsw;

@property (weak, nonatomic) IBOutlet UIButton *handleBtn;


@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

- (void)initView {
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    
    self.isShowPsw = NO;
    self.pswTF.secureTextEntry = YES;
    self.checkPswTF.secureTextEntry = YES;
    
    self.phoneTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
    self.phoneTF.leftViewMode=UITextFieldViewModeAlways;

    self.pswTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
    self.pswTF.leftViewMode=UITextFieldViewModeAlways;
    
    self.codeTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
    self.codeTF.leftViewMode=UITextFieldViewModeAlways;
    
    self.checkPswTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
    self.checkPswTF.leftViewMode=UITextFieldViewModeAlways;
    
//    self.recommandTF.leftView= [[UIView alloc]initWithFrame:CGRectMake(0,0,30,40)];
//    self.recommandTF.leftViewMode=UITextFieldViewModeAlways;
    
    // 下划线
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"注册即代表您已同意我们的《服务协议》和《隐私政策》"];
    
    [attribtStr addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xFDB44B) range:NSMakeRange(12,6)];
    [attribtStr addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xFDB44B) range:NSMakeRange(19,6)];
    
    [attribtStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(12,6)];

    [attribtStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(19,6)];

    //赋值
    self.linkText.attributedText = attribtStr;
    
    WEAKSELF
    self.linkText.userInteractionEnabled = YES;
    [self.linkText addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
            
        TT_WebviewController *vc = [[TT_WebviewController alloc] init];
        vc.webUrl = [NSString stringWithFormat:@"%@/%@", BA_GlobalPdf_Domain, kSecretPdf];
                
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.countDownBtn pp_clipCorners:UIRectCornerAllCorners radius:self.countDownBtn.frame.size.height/2];
    });
}

- (IBAction)goBack:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)codeAction:(id)sender {
    
    [self request_registerSms];
}

- (IBAction)hidePswAction:(id)sender {
    
    self.isShowPsw = !self.isShowPsw;
    if (self.isShowPsw) {
        self.pswTF.secureTextEntry = NO;
        self.checkPswTF.secureTextEntry = NO;
    } else {
        self.pswTF.secureTextEntry = YES;
        self.checkPswTF.secureTextEntry = YES;
    }
    
    if (self.isShowPsw) {
        [self.hidePswBtn setImage:[UIImage imageNamed:@"cansee"] forState:UIControlStateNormal];
        [self.hideCheckPswBtn setImage:[UIImage imageNamed:@"cansee"] forState:UIControlStateNormal];

    } else {
        [self.hidePswBtn setImage:[UIImage imageNamed:@"cantSee"] forState:UIControlStateNormal];
        [self.hideCheckPswBtn setImage:[UIImage imageNamed:@"cantSee"] forState:UIControlStateNormal];

    }
}


- (IBAction)handleAction:(id)sender {
    
    [self request_register];
}

- (void)request_register {
    
    if (self.phoneTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    
    if (self.codeTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    
    if (self.pswTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    
    if (self.checkPswTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请确认密码"];
        return;
    }else {
        
        if (![self.checkPswTF.text isEqualToString:self.pswTF.text]) {
            [SVProgressHUD showErrorWithStatus:@"两次密码输入不一致"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
    }
    
    self.handleBtn.userInteractionEnabled = NO;
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneTF.text forKey:@"userName"];
    [dic setValue:self.pswTF.text forKey:@"passWord"];
    [dic setValue:self.checkPswTF.text forKey:@"confirmPassWord"];

    [dic setValue:self.codeTF.text forKey:@"vcode"];
//    [dic setValue:self.recommandTF.text forKey:@"myCode"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_Register];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在注册"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];
        weakSelf.handleBtn.userInteractionEnabled = YES;

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                 
                [OpenInstallSDK reportRegister];
                [TTUserModel sharedObject].isRegister = YES;

                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
//                [weakSelf.navigationController popViewControllerAnimated:YES];
                [weakSelf request_login];
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
                
    } FailedBlock:^(NSError * _Nonnull error) {
        weakSelf.handleBtn.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
    }];
}

#pragma mark 账号密码登录login
- (void)request_login {

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneTF.text forKey:@"userName"];
    [dic setValue:[TTUDIDManager getUniqueDeviceID] forKey:@"alias"];

    [dic setValue:@"4" forKey:@"loginType"];
    [dic setValue:self.pswTF.text forKey:@"passWord"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Platform,API_Login];

WEAKSELF
    [SVProgressHUD showWithStatus:@"正在登录"];
    [TTHttpManager getRequestWithUrl:url TimeOut:10 GetData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSString *token = [resultDic valueForKey:@"token"];
                NSMutableDictionary *user = [resultDic valueForKey:@"user"];
                
                [[TTUserModel sharedObject].userModelDefault setValue:token forKey:@"TT_token"];
                
                BOOL isNewer = [[resultDic valueForKey:@"isNewer"] boolValue];
                [[TTUserModel sharedObject].userModelDefault setValue:isNewer?@"1":@"0" forKey:@"TT_isNewer"];
                
                [[TTUserModel sharedObject].userModelDefault synchronize];
                [[TTUserModel sharedObject] fillUserModelWithDic:user];

                if (weakSelf.completion) {
                    weakSelf.completion(YES, resultDic);
                }
                
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];

            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}


- (void)request_registerSms {

    if (self.phoneTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneTF.text forKey:@"mobile"];
    [dic setValue:@"1" forKey:@"type"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SMS];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                [weakSelf.countDownBtn startWithTime:59
                                           title:@"重新获取"
                                  countDownTitle:@"s"
                                       mainColor:UIColorHex(0xFDB44B)
                                      countColor:UIColorHex(0xFDB44B)];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
    
}

@end
